package com.weitu.workflow.definition.controller;

import com.alibaba.fastjson.JSONObject;
import com.weitu.base.controller.BaseController;
import com.weitu.base.entity.Tree;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.department.entity.Department;
import com.weitu.permission.department.service.DepartmentService;
import com.weitu.permission.roleGroup.entity.RoleGroup;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.definition.constant.FlowDefConstants;
import com.weitu.workflow.definition.entity.WorkFlowDefinition;
import com.weitu.workflow.definition.service.WorkflowDefService;
import com.weitu.workflow.flowBusiness.entity.FlowBusiness;
import com.weitu.workflow.flowBusiness.service.FlowBusinessService;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.definition.WorkflowDefinition;
import org.fireflow.engine.definition.WorkflowDefinitionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/workflow/workflowDef")
public class WorkflowDefController extends BaseController {

    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "workflow/workflowDef";
    @Autowired
    private WorkflowDefService workflowDefService;//工作流定义Service
    @Autowired
    private FlowBusinessService flowBusinessService;//流程业务标识service

    /***
     * 跳转到流程定义列表页面
     * @return
     */
    @RequestMapping(value = "/list")
    public String listView() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/demo")
    public String demo() {
        return MODULE_BATH_PATH + "/demo";
    }

    /***
     * 查询工作流列表数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/findWorkflowDefList")
    public Object findWorkflowDefList(HttpServletRequest request) {


        Map<String, Object> map = new HashMap<String, Object>();

        //获取前台参数
        this.putParametersIntoMap(map);

        Integer totalNum = this.workflowDefService.queryWorkflowDefCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);

        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView",pageView);
       // List<WorkflowDefinitionInfo> workflowDefinitionList =this.workflowDefService.queryWorkflowDefList(map);
        List<WorkFlowDefinition> workflowDefinitionList = this.workflowDefService.queryWorkflowDefTableList(map);

        return pagination.flushDataGridData(workflowDefinitionList);
    }

    /***
     * 跳转到流程定义添加页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    public ModelAndView addView(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(MODULE_BATH_PATH + "/addOrUpdate");

        String processId=request.getParameter("processId");//流程id
        modelAndView.addObject("processId",processId);
        //查询流程业务标识集合
       List<FlowBusiness> flowBusinessesIdentityList= this.flowBusinessService.queryFlowBusinessIdentityListNotWorkFlow(processId);
       modelAndView.addObject("businessIdentityList",flowBusinessesIdentityList);
        return modelAndView;
    }
    /**
     * 获取流程信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryFlowDefInfo")
    @Transactional
    public Object queryFlowDefInfo(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        //获取流程对象
        JSONObject defInfo=this.workflowDefService.queryFlowDefInfo(processId);
        return defInfo;
    }
    /**
     * 保存流程定义
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addWorkflowDef",method = RequestMethod.POST)
    @Transactional
    public AjaxResult addWorkflowDef(HttpServletRequest request){
        User crrentUser=this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String workflowDefInfoString=paramMap.get("workflowDefInfo").toString();//流程定义信息
        JSONObject workflowDef=JSONObject.parseObject(workflowDefInfoString);
        //创建或保存流程定义信息
        String processId=workflowDef.getString("processId");//流程id
        if(!(processId!=null&&!"".equals(processId.trim()))){//流程processId
            processId="WorkFlow"+DateTimeUtil.formatterDateTime("yyyyMMddHHmmss");
            workflowDef.put("processId",processId);
        }
        boolean boo=this.workflowDefService.createOrUpdateWorkflowDef(workflowDef,crrentUser);
        //保存流程id和业务标识的关联，一个业务只能对应一个流程
        boolean flag = true;
        //判断是否有该流程标识对应的业务标识，如果有则不添加
        List<FlowBusiness> flowBusinessList =  flowBusinessService.queryFlowBusinessIdentityByProcessId(processId);
        if(flowBusinessList==null||flowBusinessList.size()==0){
            Map<String,Object> businessAndProcessMap = new HashMap<String,Object>();
            String businessIdentity = workflowDef.getString("businessIdentity");//业务标识
            businessAndProcessMap.put("businessIdentity",businessIdentity);
            businessAndProcessMap.put("processId",processId);
            flag = flowBusinessService.addBusinessIdentityAndProcessId(businessAndProcessMap);
        }

        if (boo&&flag){
            result.setMessage("保存成功！");
            result.setSuccess(true);
            return result;
        }else {
            result.setMessage("保存失败！");
            result.setSuccess(false);
            return result;
        }
    }
    /***
     * 跳转到流程定义修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit")
    public ModelAndView editView(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();

        String processId=request.getParameter("processId");//流程processId
        modelAndView.addObject("processId",processId);

        //查询该工作流对应的流程业务标识
        List<FlowBusiness> flowBusinessesIdentityList= this.flowBusinessService.queryFlowBusinessIdentityByProcessId(processId);

        modelAndView.addObject("businessIdentityList",flowBusinessesIdentityList);

        modelAndView.setViewName(MODULE_BATH_PATH + "/addOrEdit");
        return modelAndView;
    }

    /***
     * 根据processId获取流程定义信息
     * @param processId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/queryWorkflowDefInfoByProcessId")
    public Object queryWorkflowDefInfoByProcessId(String processId){
        JSONObject workflowDef=this.workflowDefService.queryWorkflowDefByProcessId(processId);
        return workflowDef;
    }



    /*@ResponseBody
    @RequestMapping("/findByParam")
    public Object findByParam(HttpServletRequest request) {


        Map<String, Object> map = new HashMap<String, Object>();

       *//* //获取前台参数
        putParametersIntoMap(map);

        Integer totalNum = departmentService.findByParamCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);

        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);

        List<Department> departmentList = departmentService.findByParam(map);*//*

        return pagination.flushDataGridData(departmentList);
    }*/

    /***
     * 生成流程定义
     * @param processId 流程实例id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/generateWorkflowDef")
    public String generateWorkflowDef(HttpServletRequest request,String processId){
        String  workflowDefXml=this.workflowDefService.generateWorkflowDef(processId);
        return workflowDefXml;
    }
    /***
     * 删除流程定义副本
     * @param processId 流程实例id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/deleteWorkflowDefCopy")
    public Object deleteWorkflowDefCopy(HttpServletRequest request,String processId){
        this.workflowDefService.deleteWorkflowDefinitionCopy(processId+ FlowDefConstants.FLOWCOPY_SUFFIX);
        return true;
    }
    /***
     * 生成流程环节节点
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/generateNode")
    public Object generateNode(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        String nodeType=request.getParameter("nodeType");//节点类型
        String x=request.getParameter("x");//x坐标
        String y=request.getParameter("y");//y坐标
        String fromNodeName=request.getParameter("fromNode");//起始节点
        String toNodeName=request.getParameter("toNode");//结束节点

        Map<String,Object> params=new HashMap<String,Object>();
        params.put("processId",processId);
        params.put("nodeType",nodeType);
        params.put("x",x);
        params.put("y",y);
        params.put("fromNodeName",fromNodeName);
        params.put("toNodeName",toNodeName);

        JSONObject nodeData=this.workflowDefService.generateNode(params);
        return nodeData;
    }
    /***
     * 拖拽移动环节节点
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/dragNode")
    public Object dragNode(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        String x=request.getParameter("x");//x坐标
        String y=request.getParameter("y");//y坐标
        String nodeName=request.getParameter("nodeName");//节点名称

        Map<String,Object> params=new HashMap<String,Object>();
        params.put("processId",processId);
        params.put("x",x);
        params.put("y",y);
        params.put("nodeName",nodeName);

        JSONObject nodeData=this.workflowDefService.dragNode(params);
        return nodeData;
    }
    /***
     * 修改节点显示名称
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/updateNodeDisplayName")
    public Object updateNodeDisplayName(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        int nodeType=Integer.parseInt(request.getParameter("nodeType").toString());//节点类型
        String nodeName=request.getParameter("nodeName");//节点名称
        String displayName=request.getParameter("displayName");//节点显示名称

        //修改节点名称
        JSONObject nodeData=this.workflowDefService.updateNodeName(processId,nodeType,nodeName,displayName);
        return nodeData;
    }
    /***
     * 修改节点属性
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/updateNodeAttribute")
    public Object updateNodeAttribute(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        int nodeType=Integer.parseInt(request.getParameter("nodeType").toString());//节点类型
        String nodeName=request.getParameter("nodeName");//节点名称
        String attributeName=request.getParameter("attributeName");//属性名称
        String attributeValue=request.getParameter("attributeValue");//属性值

        //修改节点属性
        JSONObject nodeData=this.workflowDefService.updateNodeAttribute(processId,nodeType,nodeName,attributeName,attributeValue);
        return nodeData;
    }

    /***
     * 删除节点
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/deleteNode")
    public Object deleteNode(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        int nodeType=Integer.parseInt(request.getParameter("nodeType").toString());//节点类型
        String nodeName=request.getParameter("nodeName");//节点名称

        //删除节点
        JSONObject nodeData=this.workflowDefService.deleteNode(processId,nodeType,nodeName);
        return nodeData;
    }
    /***
     * 保存流程定义信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/saveFlowDef")
    public Object saveFlowDef(HttpServletRequest request){
        String processId=request.getParameter("processId");//流程id
        String businessIdentity=request.getParameter("businessIdentity");//业务标识

        //保存流程
        JSONObject nodeData=this.workflowDefService.saveFlowDef(processId);

        //保存流程业务标识
        boolean deleteFlag=this.flowBusinessService.deleteBusinessIdentityAndProcessId(processId);
        Map<String,Object> businessAndProcessMap = new HashMap<String,Object>();
        businessAndProcessMap.put("businessIdentity",businessIdentity);
        businessAndProcessMap.put("processId",processId);
        boolean saveFlag = flowBusinessService.addBusinessIdentityAndProcessId(businessAndProcessMap);
        return nodeData;
    }


}
